from django.shortcuts import redirect
import urllib

class CourseMiddleware:
    """
    Loads the course object into request.course
    """
    def process_view(self, request, view_func, view_args, view_kwargs):
        #print 'Executing process_view from CourseMiddleware'
        name = view_kwargs.get('course_name',None)
        instructor = view_kwargs.get('instructor',None)
        
        #set up request.profile
        if request.user.is_anonymous():
            request.profile = None
        else:
            from models import Profile
            request.profile = Profile.objects.get(user=request.user)
        
        if name is None or instructor is None:
            return None
            #the view isn't being sent course/instructor info.
            #returning None passes the raw request to the view.
        
        from models import Course
        request.course = Course.getByNames(
            name=view_kwargs['course_name'],
            instructor=view_kwargs['instructor']
        )
        
        
        del view_kwargs['course_name']
        del view_kwargs['instructor']
        
        return None
        #return view_func(request, *view_args, **view_kwargs)
        
        
class CourseAuthMiddleware:
    """
    Checks if the current user has the permissions to use the
    given view.  Searches the docstring of view_func for a line 
    of the form
    
    @required_level: 'narf'
    
    where 'narf' is either 'student', 'instructor', or 'admin'.
    """
        
    def process_view(self, request, view_func, view_args, view_kwargs):
        #print 'Executing process_view from CourseAuthMiddleware'
        
        if not hasattr(request, 'course'):
            return None #we're not viewing a course, so oh well.
        
        if request.profile is None:
            #from models import Profile
            
            #raise Profile.PermissionsError(
            #    '#TODO: Redirect to a page that says "You need to log in to see this"'
            #)
            from auth.views import LOGIN_PAGE_URL
            redirect_to = LOGIN_PAGE_URL + '?context=redirect&redirect_to=' + \
                request.get_full_path()
            print 'redirecting to "%s"' % redirect_to
            return redirect(redirect_to)
            
        level = request.profile.roleByCourse(request.course)
        
        if level == None:  #null role will evaluate true here.  See Role.__cmp__()
            from django.shortcuts import render_to_response
            return render_to_response('user/login/members-only.tpl',
                {
                    'course': request.course,
                    'profile': request.profile
                }
            )   
        
        #from models import Role
        
        required_level = view_func.__dict__.get('required_role', 'student') #default to student
        #print 'Checking required_level for view "%s".  The required role is "%s".  The function dictionary is: %s' % \
        #    (view_func.__name__, required_level, view_func.__dict__)
        
         
        if required_level > level:  #level here is a Role object, so comparing works always
            from django.shortcuts import render_to_response
            return render_to_response('user/login/insufficient-permissions.html',
                {
                    'course': request.course,
                    'profile': request.profile,
                    'required_role': required_level,
                    'role': level,
                }
            )
        
        return None #all checked out, continue on to the view
           
